package com.zu.commu.local.process;

import com.zu.commu.context.Config;
import com.zu.commu.interf.Action;
import com.zu.commu.interf.Command;
import com.zu.commu.interf.Order;
import com.zu.commu.interf.meter.Driver;
import com.zu.commu.interf.meter.Request;
import org.apache.log4j.Logger;

public class LocalMeterProcess
{
  private static Logger log = Logger.getLogger(
    "com.automic.commu.local.process.LocalMeterProcess");

  public String processData(String gprsId, Order order, Command command, byte[] bs)
  {
    Request request = getRequest(gprsId);
    if (request == null)
    {
      String error = "没有得到GPRS ID为" + gprsId + "的测控器的协议。可能配置的GPRS ID与实际的不相附合,也可能通信服务器现在没有得到对应这个GPRS ID的测控器通信协议！";
      log.error(error);
      return error;
    }
    String r = "";
    try {
      Action action = request.analyseOrder(order, command);
      if (Action.SENDREMOTE.equals(action))
      {
        byte[] buf = request.getRemoteData();
        r = sendRemoteByThread(gprsId, order, command, buf);
      } else if (Action.SENDREMOTESINGLE.equals(action))
      {
        byte[] buf = request.getRemoteData();
        r = sendRemoteDirectSingle(gprsId, order, command, buf);
      } else if (Action.ERROR.equals(action)) {
        String er = request.getError();
        if (er == null) {
          er = "发生错误，可能对应的测控器不支持此命令。";
        }
        log.error(er);
        return er;
      }
    }
    catch (Exception localException)
    {
    }

    return r;
  }

  public String sendRemoteByThread(String gprsId, Order order, Command command, byte[] buf)
  {
    LocalGprsProcess nextProcess = new LocalGprsProcess();
    return nextProcess.processDataAndSendByThread(gprsId, command, order, buf);
  }

  public String sendRemoteDirectSingle(String gprsId, Order order, Command command, byte[] buf)
  {
    LocalGprsProcess nextProcess = new LocalGprsProcess();
    return nextProcess.processDataAndSendDirectSingle(gprsId, command, order, buf);
  }

  public String sendRemoteDirect(String gprsId, Order order, Command command, byte[] buf)
  {
    LocalGprsProcess nextProcess = new LocalGprsProcess();
    return nextProcess.processDataAndSendDirect(gprsId, command, order, buf);
  }

  private Request getRequest(String gprsId)
  {
    Request r = null;
    try
    {
      Config cf = Config.instance();
      String protocol = cf.getMeterProcotolOfGPRSID(gprsId);
      if (protocol != null)
      {
        Driver driver = cf.getDriverOfMeterProtocol(protocol);
        r = driver.getRequest();
      }
    }
    catch (Exception localException)
    {
    }

    return r;
  }
}